/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package PuriON;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.media.format.UnsupportedFormatException;
import javax.media.protocol.DataSource;
import javax.media.rtp.InvalidSessionAddressException;
import javax.media.rtp.RTPManager;
import javax.media.rtp.SendStream;
import javax.media.rtp.SessionAddress;

/**
 *
 * @author hyukmini
 */


public class PURION_MultiTransmit implements Runnable {
    
    private volatile int sCount = 0;
    
    RTPManager[] rtpMgrs = null ;
    DataSource dataOutput = null;
    String ipAddress = null;
    int port;
    
    public PURION_MultiTransmit(RTPManager[] _r, DataSource _d, String _i, int _p) {
        
        rtpMgrs = _r;
        dataOutput = _d;
        
        ipAddress = _i;
        port = _p;
    }
    
    public void addTarget() {

        try {
            System.err.println("PURION_Transmit : Created RTP Session for IP (" + ipAddress + "/" + port + ")");
            
            for(int i = 0; i < rtpMgrs.length; i++) {            
                Thread t1 = new Thread(new SendData(rtpMgrs[i], dataOutput, ipAddress, 30000 + 2 * i ,sCount));
                t1.start();
                sCount++;
            }
        }
        /*
        // SendStream : 스트리밍을 보낼 때 지원되지 않는 파일 포맷일 때 예외처리
*/
        catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    public void run() {
        addTarget();
    }
}

class SendData implements Runnable{
    
    private int sCount = 0;
    
    RTPManager rtpMgrs = null ;
    DataSource dataOutput = null;
    int port;
    InetAddress address = null;
    
    public SendData(RTPManager _r, DataSource _d, String _i, int _p, int _s) {
        rtpMgrs = _r;
        dataOutput = _d;
        port = _p;
        sCount = _s;
        try {
            address = InetAddress.getByName(_i);
        } 
        catch (UnknownHostException e) {
            System.err.println("PURION_Transmit(Unknown Host) :" + e.getMessage());
        }

    }
    public void run() {
        System.out.println("Asdf");
        try {
            SessionAddress destAddr = new SessionAddress(address, port);
            rtpMgrs.addTarget(destAddr);
            SendStream sendStream = rtpMgrs.createSendStream(dataOutput, sCount);
            sendStream.start();
        }
  // InetAddress : 주소가 잘못된 값이 입력되었을 때 예외처리
        catch (InvalidSessionAddressException e) {
            System.err.println("PURION_Transmit(Invalid Address):" + e.getMessage());
        } catch (UnsupportedFormatException e) {
            System.err.println("PURION_Transmit(Not Supported Format):" + e.getMessage());
        }
        catch(IOException e) {
            System.err.println("PURION_Transmit(IO EX):" + e.getMessage());
        }
    }
}
